import { Checkbox, Divider, Flex, Input, message, Modal, Space, Table, Tooltip, Typography } from "antd";
import { forwardRef, useImperativeHandle, useRef, useMemo, useState } from "react";
import StringEditor from "./StringEditor";
import { editRedisKey, deleteKey } from "@/api/sharing/redis";
import { QuestionCircleOutlined, ExclamationCircleFilled } from "@ant-design/icons";

const ListValue = ({ currentSource, fullData, isFetching, refetch, onTransferLeftPanel }, ref) => {
  const [selectedRowKeys, setSelectedRowKeys] = useState([])
  const [selectedRow, setSelectedRow] = useState(null)
  const panelStringRef = useRef()
  const tableData = useMemo(() => {
    return (fullData?.result || []).map((value, index) => {
      const opt = {
        field: index + '',
        value: value
      }
      if (selectedRowKeys[0] === opt.field) {
        setSelectedRow({ ...opt })
      }
      return opt
    })
  }, [fullData])

  const onSelectChange = (selectedRowKeys, selectedRows,) => {
    if (selectedRowKeys.length) {
      setSelectedRowKeys([selectedRowKeys[selectedRowKeys.length - 1]]);
      setSelectedRow(selectedRows[selectedRowKeys.length - 1])
    } else {
      setSelectedRow(null)
      setSelectedRowKeys([])
    }
  }

  const handleSave = () => {
    if (!selectedRow) {
      message.error('请先选择一行')
      return
    }
    editRedisKey({
      id: currentSource?.connectInfo?.id,
      key: currentSource.key,
      index: selectedRow?.field,
      database: currentSource.database,
      serializer: selectedRow.serializer,
      value: selectedRow.value,
      dataType: currentSource.tag.toLocaleUpperCase()
    }).then((res) => {
      if (res.code == 200) {
        message.success('保存成功')
        if (!selectedRowKeys.length) {
          setSelectedRow(null)
          setSelectedRowKeys([])
        }
        refetch()
      }
    })
  }

  const handleDelete = (record) => {
    const handle = () => {
      return deleteKey({
        id: currentSource?.connectInfo?.id,
        key: currentSource.key,
        value: record.value,
        database: currentSource.database,
        type: currentSource.tag.toLocaleUpperCase()
      }).then((res) => {
        if (res.code == 200) {
          message.success('删除成功')
          if (tableData.length == 1) {
            onTransferLeftPanel('deleteKey', {
              id: currentSource?.connectInfo.id,
              database: currentSource?.database,
              key: currentSource?.key,
              type: currentSource?.tag.toLocaleUpperCase(),
            })
          } else {
            refetch()
            if (selectedRowKeys.includes(record.field)) {
              setSelectedRow(null)
              setSelectedRowKeys([])
            }
          }
        }
      })
    }

    if (tableData.length == 1) {
      Modal.confirm({
        title: '此行数据是该键最后一行数据。删除此行数据，该键将会被删除',
        icon: <ExclamationCircleFilled />,
        autoFocusButton: null,
        onOk() {
          return handle()
        },
        onCancel() { },
      });
    } else {
      handle()
    }
  }

  useImperativeHandle(ref, () => ({
    save: handleSave
  }))

  return (
    <>

      <div className='right-panel-table'>

        <Table
          rowSelection={{ type: 'checkbox', hideSelectAll: true, selectedRowKeys: selectedRowKeys, onChange: onSelectChange }}
          onRow={(record) => ({
            onClick: () => {
              if (selectedRowKeys.includes(record.field)) {
                setSelectedRow(null)
                setSelectedRowKeys([])
              } else {
                setSelectedRow(record)
                setSelectedRowKeys([record.field])
              }
            }
          })}
          rowKey={(record) => record.field}
          loading={isFetching}
          dataSource={tableData}
          pagination={false}
          scroll={{ y: 400 }}
          columns={
            [
              {
                dataIndex: 'no',
                title: '行号',
                width: 60,
                align: 'center',
                render(text, _, index) {
                  return index + 1
                },
              },
              // {
              //   dataIndex: 'field',
              //   title: '键名',
              //   width: 120,
              //   ellipsis: true,
              // },
              {
                dataIndex: 'value',
                title: '键值',
                width: 160,
                ellipsis: true,
              },
              {
                dataIndex: 'action',
                title: '操作',
                width: 50,
                render(_, record) {
                  return <>
                    <a onClick={() => setSelectedRow(record)}>编辑</a>
                    <Divider type="vertical" />
                    <a onClick={() => handleDelete(record)}><Typography.Text type="danger">删除</Typography.Text></a>
                  </>
                }
              }
            ]
          }
        />
      </div>
      <Flex style={{ marginTop: 20 }} align='center'>
        <Checkbox style={{ flexShrink: 0 }} disabled={!currentSource} checked={selectedRow?.serializer} onChange={(e) => {
          setSelectedRow({
            ...(selectedRow || {}),
            serializer: e.target.checked
          })
        }}>
          <Space>
            <span>使用JDK序列化</span>
            <Tooltip overlayStyle={{ maxWidth: 300 }} placement='left' title={`JDK序列化说明： 默认作为 String 类型来序列化。
            若内容带有类型提示: 如 123♣java.lang.Long => 将转换为 Long 类型来序列化；
            若希望转换为复杂对象来序列化，则可以这样表示： ["java.util.ArrayList",
            [{"@class":"cn.com.bluemoon.invocationlab.admin.rpcpostman.model.erd.AesReqVo",
            "projectId":"2011yhfdsaa","opType":1,"value":898}]] => 将转换为为
            ArrayList<AesReqVo> 类型来序列化(如果能找到对应的class且class实现了Serializable接口)`}>
              <QuestionCircleOutlined />
            </Tooltip>
          </Space>
        </Checkbox>
      </Flex>
      <StringEditor ref={panelStringRef} readOnly={!currentSource} value={selectedRow?.value} onChange={(value) => setSelectedRow({
        ...(selectedRow || {}),
        value
      })} />
    </>
  );
}

export default forwardRef(ListValue);